<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <el-card class="profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="8">
          <div class="avatar-container">
            <el-avatar :size="120" :src="userInfo.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            <el-upload class="avatar-uploader" action="#" :http-request="handleAvatarUpload" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <el-button type="primary" size="small" class="upload-btn">更换头像</el-button>
            </el-upload>
          </div>
        </el-col>

        <el-col :xs="24" :sm="16" :md="16">
          <div class="info-container">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="账号">{{ userInfo.username }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="身份">管理员</el-descriptions-item>
              <el-descriptions-item label="登录时间">{{ loginTime }}</el-descriptions-item>
            </el-descriptions>

            <el-button type="primary" @click="passwordDialogVisible = true" class="change-pwd-btn">
              修改密码
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 系统信息统计卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" class="stat-col">
        <el-card class="stat-card" shadow="hover">
          <!-- 上部分：标题 -->
          <template #header>
            <div class="card-header">
              <span>学生统计</span>
              <el-icon class="stat-icon">
                <User />
              </el-icon>
            </div>
          </template>

          <!-- 中部分：内容 -->
          <div class="stat-content">
            <div class="stat-title">学生总数</div>
            <div class="stat-value">{{ statistics.studentCount || '0' }} <span class="stat-unit">人</span></div>
          </div>

          <!-- 下部分：操作区域 -->
          <div class="stat-footer">
            <el-button type="primary" link @click="$router.push('/admin/students')">管理学生</el-button>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" class="stat-col">
        <el-card class="stat-card" shadow="hover">
          <!-- 上部分：标题 -->
          <template #header>
            <div class="card-header">
              <span>体测项目统计</span>
              <el-icon class="stat-icon">
                <List />
              </el-icon>
            </div>
          </template>

          <!-- 中部分：内容 -->
          <div class="stat-content">
            <div class="stat-title">体测项目数</div>
            <div class="stat-value">{{ statistics.sportItemCount || '0' }} <span class="stat-unit">项</span></div>

            <div class="stat-details">
              <div class="detail-row">
                <span>通用项目:</span>
                <span class="stat-number">{{ statistics.commonItemCount || '0' }}</span>
              </div>
              <div class="detail-row">
                <span>男生项目:</span>
                <span class="stat-number">{{ statistics.maleItemCount || '0' }}</span>
              </div>
              <div class="detail-row">
                <span>女生项目:</span>
                <span class="stat-number">{{ statistics.femaleItemCount || '0' }}</span>
              </div>
            </div>
          </div>

          <!-- 下部分：操作区域 -->
          <div class="stat-footer">
            <el-button type="primary" link @click="$router.push('/admin/sport-items')">管理项目</el-button>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" class="stat-col">
        <el-card class="stat-card" shadow="hover">
          <!-- 上部分：标题 -->
          <template #header>
            <div class="card-header">
              <span>成绩统计</span>
              <el-icon class="stat-icon">
                <Document />
              </el-icon>
            </div>
          </template>

          <!-- 中部分：内容 -->
          <div class="stat-content">
            <div class="stat-title">成绩记录数</div>
            <div class="stat-value">{{ statistics.scoreCount || '0' }} <span class="stat-unit">条</span></div>
          </div>

          <!-- 下部分：操作区域 -->
          <div class="stat-footer">
            <el-button type="primary" link @click="$router.push('/admin/scores')">管理成绩</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统通知卡片 -->
    <el-card class="notice-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>最近公告</h3>
          <el-button type="primary" link @click="$router.push('/admin/announcements')">管理公告</el-button>
        </div>
      </template>
      <el-timeline v-if="recentAnnouncements.length > 0">
        <el-timeline-item v-for="(announcement, index) in recentAnnouncements" :key="announcement.id" :timestamp="formatDate(announcement.publishTime)" :type="getAnnouncementType(index)" placement="top" :hollow="index > 0">
          <div class="announcement-item" @click="viewAnnouncementDetail(announcement)">
            <span class="announcement-title">{{ announcement.title }}</span>
            <span class="announcement-publisher">发布人：{{ announcement.publisherName }}</span>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无公告" />
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo, getToken, updateUserInfo } from '@/utils/auth'
import { changePassword } from '@/api/user'
import { uploadAvatar } from '@/api/upload'
import { getAnnouncements } from '@/api/announcement'
import { getSportItems } from '@/api/sportItem'
import { countStudents } from '@/api/student'
import { countScores } from '@/api/score'
import { useRouter } from 'vue-router'
import { User, List, Document } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/format'

const router = useRouter()

// 用户信息
const userInfo = ref({})

// 登录时间
const loginTime = computed(() => {
  // 从localStorage获取登录时间，如果没有则使用当前时间
  const loginTimeStr = localStorage.getItem('loginTime')
  const time = loginTimeStr ? new Date(parseInt(loginTimeStr)) : new Date()
  return formatDate(time, 'YYYY-MM-DD HH:mm:ss')
})

// 系统统计数据
const statistics = reactive({
  studentCount: 0,
  sportItemCount: 0,
  scoreCount: 0,
  commonItemCount: 0,
  maleItemCount: 0,
  femaleItemCount: 0
})

// 最近公告
const recentAnnouncements = ref([])

// 获取本地存储的用户信息
onMounted(async () => {
  // 先使用本地存储的用户信息
  userInfo.value = getUserInfo() || {}

  // 尝试获取最新用户信息
  await updateUserInfo()
  // 重新获取最新的用户信息
  userInfo.value = getUserInfo() || {}

  // 如果没有登录时间，设置当前时间
  if (!localStorage.getItem('loginTime')) {
    localStorage.setItem('loginTime', Date.now().toString())
  }

  // 获取系统统计数据
  fetchStatistics()

  // 获取最近公告
  fetchRecentAnnouncements()
})

// 获取系统统计数据
const fetchStatistics = async () => {
  try {
    // 获取体测项目数据
    const sportItemRes = await getSportItems()
    if (sportItemRes.code === 200) {
      const sportItems = sportItemRes.data || []
      statistics.sportItemCount = sportItems.length
      // 统计不同性别的项目数量
      statistics.commonItemCount = sportItems.filter(item => item.genderScope === '通用').length
      statistics.maleItemCount = sportItems.filter(item => item.genderScope === '男').length
      statistics.femaleItemCount = sportItems.filter(item => item.genderScope === '女').length
    }

    // 获取学生数量
    try {
      const studentRes = await countStudents()
      if (studentRes.code === 200) {
        statistics.studentCount = studentRes.data
      }
    } catch (e) {
      statistics.studentCount = 152 // 使用默认值
    }

    // 获取成绩数量
    try {
      const scoreRes = await countScores()
      if (scoreRes.code === 200) {
        statistics.scoreCount = scoreRes.data
      }
    } catch (e) {
      statistics.scoreCount = 437 // 使用默认值
    }
  } catch (error) {
    // 使用默认模拟数据
    statistics.sportItemCount = 8
    statistics.commonItemCount = 3
    statistics.maleItemCount = 2
    statistics.femaleItemCount = 3
    statistics.studentCount = 152
    statistics.scoreCount = 437
  }
}

// 获取最近公告
const fetchRecentAnnouncements = async () => {
  try {
    const res = await getAnnouncements()
    // 获取最近的3条公告
    recentAnnouncements.value = res.data.sort((a, b) => {
      return new Date(b.publishTime) - new Date(a.publishTime)
    }).slice(0, 3)
  } catch (error) {
    ElMessage.error('获取最近公告失败，请稍后重试')
  }
}

// 根据索引获取公告类型（用于时间线显示不同颜色）
const getAnnouncementType = (index) => {
  const types = ['primary', 'success', 'warning', 'info']
  return types[index % types.length]
}

// 查看公告详情
const viewAnnouncementDetail = (announcement) => {
  // 跳转到公告详情页或打开详情弹窗
  router.push(`/admin/announcements?view=${announcement.id}`)
}

// 头像上传相关
const handleAvatarUpload = async (options) => {
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)

  try {
    // 在开发环境中模拟头像上传
    if (import.meta.env.DEV && import.meta.env.VITE_USE_MOCK === 'true') {
      // 模拟网络请求延迟
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 创建临时URL作为上传后的头像URL
      const avatarUrl = URL.createObjectURL(file)

      // 更新用户信息
      userInfo.value.avatarUrl = avatarUrl

      // 更新本地存储的用户信息
      const storedUserInfo = getUserInfo()
      if (storedUserInfo) {
        storedUserInfo.avatarUrl = avatarUrl
        localStorage.setItem('userInfo', JSON.stringify(storedUserInfo))
      }

      ElMessage.success('头像上传成功')
      return
    }

    // 使用API上传头像
    ElMessage.info('正在上传头像...')
    const res = await uploadAvatar(formData)

    if (!res.data || !res.data.url) {
      throw new Error('上传失败，未获取到有效的头像URL')
    }

    // 上传成功后，从服务器获取最新的用户信息
    await updateUserInfo()
    // 刷新页面用户信息
    userInfo.value = getUserInfo() || {}

    ElMessage.success('头像上传成功')
  } catch (error) {
    ElMessage.error(error.message || '头像上传失败，请稍后重试')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }

  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }

  return isImage && isLt2M
}

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const changingPassword = ref(false)

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleChangePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) return

    changingPassword.value = true

    try {
      // 在开发环境中模拟密码修改
      if (import.meta.env.DEV) {
        // 模拟网络请求延迟
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 密码强度检查 - 模拟密码太简单的情况
        if (passwordForm.newPassword === '123456') {
          throw new Error('密码过于简单，请设置更复杂的密码')
        }

        ElMessage.success('密码修改成功，请重新登录')

        // 模拟清除登录信息并跳转到登录页
        setTimeout(() => {
          // 清除token和用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 跳转到登录页
          router.push('/')
        }, 1500) // 延迟1.5秒，让用户看到成功提示

        return
      }

      // 生产环境下使用真实API
      await changePassword({
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })

      ElMessage.success('密码修改成功，请重新登录')

      // 密码修改成功后，清除登录信息并跳转到登录页
      setTimeout(() => {
        // 清除token和用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        // 跳转到登录页
        router.push('/')
      }, 1500) // 延迟1.5秒，让用户看到成功提示

    } catch (error) {
      // 显示错误信息
      if (error.message && (error.message.includes('JWT') || error.message.includes('token'))) {
        ElMessageBox.confirm(
          '您的登录已过期，需要重新登录',
          '会话过期',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 清除token和用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 跳转到登录页
          router.push('/')
        }).catch(() => { })
      } else {
        ElMessage.error(error.message || '密码修改失败，请稍后重试')
      }
    } finally {
      changingPassword.value = false
      passwordDialogVisible.value = false
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }
  })
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.profile-card,
.stat-card,
.notice-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.profile-card:hover,
.notice-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.upload-btn {
  margin-top: 15px;
}

.info-container {
  padding: 20px;
}

.change-pwd-btn {
  margin-top: 20px;
}

.el-row {
  margin-bottom: 20px;
}

.stat-col {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stat-icon {
  font-size: 18px;
  color: #409EFF;
}

.stat-content {
  display: flex;
  flex-direction: column;
  padding: 20px;
  flex: 1;
  overflow: auto;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.2;
  margin-bottom: 20px;
}

.stat-unit {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
  margin-left: 5px;
}

.stat-details {
  margin-top: 0;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  background-color: #f7f9fc;
  padding: 8px 12px;
  border-radius: 4px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.stat-number {
  color: #409EFF;
  font-weight: 600;
}

.stat-footer {
  height: 46px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 20px;
  border-top: 1px solid #EBEEF5;
  background-color: #f7f9fc;
}

.el-timeline {
  padding: 0;
  margin-top: 10px;
}

.announcement-item {
  display: flex;
  flex-direction: column;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

.announcement-item:hover {
  background-color: #f0f7ff;
}

.announcement-item:hover .announcement-title {
  color: #409EFF;
}

.announcement-title {
  font-weight: 500;
  font-size: 15px;
  margin-bottom: 4px;
  transition: color 0.3s;
}

.announcement-publisher {
  font-size: 13px;
  color: #909399;
}

:deep(.el-timeline-item__node--primary) {
  background-color: #409EFF;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67C23A;
}

:deep(.el-timeline-item__node--warning) {
  background-color: #E6A23C;
}

:deep(.el-timeline-item__node--info) {
  background-color: #909399;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 13px;
}

.stat-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
}

@media screen and (max-width: 768px) {
  .stat-value {
    font-size: 28px;
  }

  .avatar-container {
    padding: 10px;
  }

  .info-container {
    padding: 10px;
  }
}
</style>